﻿using Prism.Commands;
using Prism.Events;
using Prism.Mvvm;
using Prism.Services.Dialogs;
using System;
using ZDK.Infra.Events;
using ZDK.Infra.Services;

namespace ZDK.ViewModels
{
    public class SettingsViewModel : BindableBase, IDialogAware
    {

        ICfgService _cfgSvc;
        readonly IEventAggregator _evtAggr;

        #region 绑定属性

        private int listenPort;
        public int ListenPort { get => listenPort; set => SetProperty(ref listenPort, value); }

        private bool is4GMode = true;
        public bool Is4GMode { get => is4GMode; set => SetProperty(ref is4GMode, value); }
        private string terminalId;
        public string TerminalId { get => terminalId; set => SetProperty(ref terminalId, value); }

        #endregion

        public SettingsViewModel(ICfgService cfgSvc, IEventAggregator evtAggr)
        {
            _cfgSvc = cfgSvc;
            _evtAggr = evtAggr;
            var cfg = _cfgSvc.Get();
            ListenPort = cfg.net.listenPort;
            Is4GMode = cfg.net.is4GMode;
            TerminalId = cfg.net.terminalId;
        }

        #region IDialogAware
        public string Title => "设置窗口";

        public event Action<IDialogResult> RequestClose;

        public bool CanCloseDialog()
        {
            return true;
        }

        public void OnDialogClosed()
        {
            //只要关闭就保存配置
            RequestClose?.Invoke(new DialogResult(ButtonResult.Yes));

            //保存设置参数
            var cfg = _cfgSvc.Get();
            cfg.net.listenPort = ListenPort;
            cfg.net.is4GMode = Is4GMode;
            cfg.net.terminalId = TerminalId;
            _cfgSvc.Save();
        }

        public void OnDialogOpened(IDialogParameters parameters)
        {

        }
        #endregion

        #region Command

        private DelegateCommand toggle4GModeCmd;
        public DelegateCommand Toggle4GModeCmd => toggle4GModeCmd ?? (toggle4GModeCmd = new DelegateCommand(Toggle4GMode));
        void Toggle4GMode() 
        {
            if(!Is4GMode)
            {
                //非4G模式，可直接调试
                _evtAggr.GetEvent<Is4GModeEvent>().Publish(Is4GMode);
            }
        }


        #endregion
    }
}
